Memory Alignment

Why to align

  • The scenario below causes unnecessary wastage of CPU cycles.

  • .

  • If we use padding (empty space) we can improve the CPU cycles, at the cost of the struct storing more memory.

  • .

  • .

  • The order of the elements matters, as it can introduce more padding than necessary:

  • .

  • .

Memory Access

  • Processors don't read 1 byte at a time from memory.

  • They read 1 word  at a time.

  • 32-bit Processor :

    • Word size is 4 bytes.

  • 64-bit Processor :

    • Word size is 8 bytes.

Size

  • The total number of bytes that a single element actually occupies in memory, including  any internal padding required by alignment.

Offset

  • Defines where a field resides relative to a structure’s base address.

  • Example :

    • In struct { int a; char b; } , if a  starts at offset 0 , b  might be at offset 4  due to alignment padding.

Stride

  • Byte distance between consecutive elements in an array or buffer.

  • It’s not “after the element finishes”, it’s the total distance between consecutive starts .

  • That’s why stride includes all bytes (data + padding) in a single element.

  • Example :

    • In a vertex buffer with position (12 bytes) + color (4 bytes), stride = 16 bytes. The next vertex starts 16 bytes after the previous one.

      • Vertex 0 starts at byte 0 .

      • Vertex 0 occupies bytes 0–15 .

      • Vertex 1 starts at byte 16 .